package net.tngou.util;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;



/**

 * Http请求  get与Post

 * @author 陈磊

 *

 */

public class HttpUtil {

	private static final Logger log= LoggerFactory.getLogger(HttpUtil.class);
	private static HttpConfig httpConfig = HttpConfig.getInstance();
	
	
	/**

	 * 取得页面信息

	* <p>Title: get<／p>

	* <p>Description: <／p>

	* @param url

	* @return

	 */
	public static Document get(String url) {
		Document doc = null;
		
		try {
			doc = Jsoup.connect(url).
					timeout(httpConfig.getTimeout()).
					userAgent(httpConfig.getUserAgent()).
					ignoreContentType(true).
					get();
			Entities.EscapeMode.base.getMap().clear();
		} catch (IOException e) {

//			e.printStackTrace();

			log.error("取得HTTP请求{}出错！",url);
			return null;
		}
		return doc;
		
	}
	
	public static Document post(String url) {
		Document doc = null;
		
		try {
			doc = Jsoup.connect(url).
					timeout(httpConfig.getTimeout()).
					userAgent(httpConfig.getUserAgent()).
					ignoreContentType(true).
					post();
			Entities.EscapeMode.base.getMap().clear();
		} catch (IOException e) {
//			e.printStackTrace();

			log.error("取得HTTP请求{}出错！",url);
			return null;
		}
		return doc;
		
	}
	
	/**

	 * 

	 * @param url   请求的URL

	 * @param data  参数

	 * @return

	 */
	public static Document post(String url,Map<String, String> data) {
		Document doc = null;
		try {
			
			
			doc = Jsoup.connect(url).data(data).
					timeout(httpConfig.getTimeout()).
					userAgent(httpConfig.getUserAgent()).
					ignoreContentType(true).
					post();
		} catch (IOException e) {
//			e.printStackTrace();

			log.error("取得HTTP请求{}出错！",url);
			return null;
		}
		return doc;
		
	}
	
	public static Document get(String url,Map<String, String> data) {
		Document doc = null;
		try {
			
			
			doc = Jsoup.connect(url).data(data).
					timeout(httpConfig.getTimeout()).
					userAgent(httpConfig.getUserAgent()).
					ignoreContentType(true).
					get();
		} catch (IOException e) {
//			e.printStackTrace();

			log.error("取得HTTP请求{}出错！",url);
			return null;
		}
		return doc;
		
	}
	
	public static JSONObject getJSONObject(String url,Map<String, String> data) {
		JSONObject json = new JSONObject();
		CloseableHttpClient httpclient = HttpClients.createDefault();  
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	    Set<String> set = data.keySet();
	    
		set.forEach(e->{nvps.add(new BasicNameValuePair(e, data.get(e)));});
        
		try {
        	
        	
			URI uri = new URIBuilder(url).setParameters(nvps) .build();
        	// 创建httpget.    

            HttpGet httpget = new HttpGet(uri);  
            httpget.addHeader("User-Agent", httpConfig.getUserAgent());
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout( httpConfig.getTimeout()).setConnectTimeout(httpConfig.getTimeout()).build();//设置请求和传输超时时间      

            httpget.setConfig(requestConfig);
           // httpget.s

			CloseableHttpResponse response = httpclient.execute(httpget);
			// 获取响应实体    

            HttpEntity entity = response.getEntity();
     
            String result = EntityUtils.toString(entity,"UTF-8");
        	json = JSON.parseObject(result);
            response.close(); 
		} catch (IOException | URISyntaxException e) {
			// TODO Auto-generated catch block

			e.printStackTrace();
		} finally
		{
			try {
				httpclient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block

				e.printStackTrace();
			}
		}
		
		return json;
		
	}
	public static void main(String[] args) {
		get("http://www.tngou.net");
	}
}

